package com.dxyxx.framework;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;
import zrc.widget.ZrcListView.OnStartListener;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dxyxx.R;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.Comment;
import com.dxyxx.pojo.CommentRecords;
import com.dxyxx.pojo.ResponseResult;
import com.dxyxx.utils.RelativeDateFormat;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.weixinninegridlayout.CustomImageView;
import com.weixinninegridlayout.Image;
import com.weixinninegridlayout.NineGridlayout;
import com.weixinninegridlayout.ScreenTools;

public class ProductCommentActivity extends BaseActivity {
	private final static String FROM = "from";
	private final static String TIME = "time";
	private final static String IMAGE = "image";
	private final static String WORD = "word";
	private final static String ID = "id";
	private final static String THUMB = "thumb";
	private final static int COUNT = 5;

	private Context self;

	private String pid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_comment);
		self = this;
		initViews();
		setGrid();

	}

	private void initViews() {
		Bundle bundle = this.getIntent().getExtras();
		pid = bundle.getString("productId");
		((ImageView) findViewById(R.id.backImageButton)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();

			}
		});
		ImageView next = (ImageView) findViewById(R.id.nextImageButton);
		next.setVisibility(View.INVISIBLE);

		((TextView) findViewById(R.id.title)).setText("商品评论");
		((TextView) findViewById(R.id.title)).setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
	}

	/**
	 * 添加ListView
	 * 
	 */
	private ZrcListView listView;
	private ViewGroup waitViewGroup;
	private View container;
	private MessageAdapter messageAdapter;
	private List<Map<String, String>> data;
	private LayoutInflater mInflater;
	private int currentPage = 1; // 当前加载页数

	// **设置listview 头部底部的样式
	private void setStyle(ZrcListView listView) {
		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		SimpleHeader header = new SimpleHeader(self);
		header.setTextColor(0xff0066aa);
		header.setCircleColor(0xff33bbee);
		listView.setHeadable(header);

		// 设置加载更多的样式（可选）
		SimpleFooter footer = new SimpleFooter(self);
		footer.setCircleColor(0xff33bbee);
		listView.setFootable(footer);

		// 设置列表项出现动画（可选）
		listView.setItemAnimForTopIn(R.anim.topitem_in);
		listView.setItemAnimForBottomIn(R.anim.bottomitem_in);

		// 开启 加载更多多 的功能
		listView.startLoadMore();
	}

	private void setGrid() {
		mInflater = LayoutInflater.from(self);
		waitViewGroup = (ViewGroup) mInflater.inflate(R.layout.fragment_wait, null);
		container = mInflater.inflate(R.layout.component_comment_mylistview, null);
		listView = (ZrcListView) container.findViewById(R.id.zListView);
		listView.setDivider(getResources().getDrawable(R.color.common_list_devider_color));
		listView.setDividerHeight(2);

		setStyle(listView);
		data = new ArrayList<Map<String, String>>();
		messageAdapter = new MessageAdapter(self, data);

		//callNetwork();

		String urlString1 = "comment/listByPid?pid=" + pid + "&current=1&count=" + COUNT;
		HttpUtil.get(urlString1, new DownloadCommentHandler(listView, waitViewGroup, messageAdapter, false));

		// 下拉刷新事件回调（可选）
		listView.setOnRefreshStartListener(new OnStartListener() {
			@Override
			public void onStart() {
				refresh();
			}
		});

		// 加载更多事件回调（可选）
		listView.setOnLoadMoreStartListener(new OnStartListener() {
			@Override
			public void onStart() {
				loadMore();
			}
		});

		// 增加  等待框架到  linearLayout

		LinearLayout ll = (LinearLayout) findViewById(R.id.vp_message_launcher_layout);
		ll.addView(waitViewGroup);

	}

	private void refresh() {

		String urlString = "comment/listByPid?pid=" + pid + "&current=1&count=" + COUNT;
		data = new ArrayList<Map<String, String>>();

		HttpUtil.get(urlString, new DownloadCommentHandler(listView, waitViewGroup, messageAdapter, true));

		// adapter.notifyDataSetChanged();
		// listView1.setRefreshSuccess("加载成功"); // 通知加载成功
		// listView1.startLoadMore(); // 开启LoadingMore功能

	}

	private void loadMore() {
		currentPage = currentPage + 1;

		String urlString = "comment/listByPid?pid=" + pid + "&current=" + currentPage + "&count=" + COUNT;

		HttpUtil.get(urlString, new DownloadMoreCommentHandler(listView, waitViewGroup, messageAdapter, data));

	}

	// 异步下载信息

	private SimpleDateFormat sdf;

	private ViewHolder holder = null; // 如果缓存convertView为空，则需要创建View

	public class MessageAdapter extends BaseAdapter {
		private List<Map<String, String>> data;

		public MessageAdapter(Context context, List<Map<String, String>> data) {
			this.mInflater = LayoutInflater.from(context);
			this.data = data;

		}

		// ViewHolder静态类
		private LayoutInflater mInflater = null;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Map<String, String> map = this.data.get(position);

			holder = null;

			//int type = getItemViewType(position);
			if (convertView == null) {// 如果缓存convertView为空，则需要创建View
				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.item_ninegridlayout, parent, false);

				holder.ivMore = (NineGridlayout) convertView.findViewById(R.id.iv_ngrid_layout);
				holder.ivOne = (CustomImageView) convertView.findViewById(R.id.iv_oneimage);
				holder.wordText = (TextView) convertView.findViewById(R.id.text);
				holder.timeText = (TextView) convertView.findViewById(R.id.time);
				holder.nameText = (TextView) convertView.findViewById(R.id.name);
				holder.thumbView = (ImageView) convertView.findViewById(R.id.thumbImage);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();

			//			List<Image> itemList = new ArrayList<Image>();
			//			String[] images = map.get("IMAGES").split(";");
			//			for (String str : images) {
			//				
			//				 String[] info = str.split("_");
			//				itemList.add(new Image(baseImageURL + info[0], Integer.parseInt(info[1]), Integer.parseInt(info[2])));
			//			}
			List<Image> itemList = new ArrayList<Image>();
			String[] images = map.get(IMAGE).split(";");
			for (String str : images) {

				String[] info = str.split("_");
				itemList.add(new Image(baseImageURL + info[0] + "?p=0", Integer.parseInt(info[1]), Integer.parseInt(info[2])));
			}
			if (itemList.size() == 0) {
				holder.ivMore.setVisibility(View.GONE);
				holder.ivOne.setVisibility(View.GONE);
			} else if (itemList.size() == 1) {
				holder.ivMore.setVisibility(View.GONE);
				holder.ivOne.setVisibility(View.VISIBLE);

				handlerOneImage(holder, itemList.get(0));
			} else {
				holder.ivMore.setVisibility(View.VISIBLE);
				holder.ivOne.setVisibility(View.GONE);
				holder.ivMore.setImagesData(map.get(IMAGE),itemList);
				//holder.ivMore.setImagesData(itemList);
			}

			//			holder.moneyText.setText(map.get(MONEY));
			//			holder.dateText.setText(map.get(DATE));
			//			holder.timeText.setText(map.get(TIME));
			//			holder.uuidText.setText(map.get(UUID));
			holder.wordText.setText(map.get(WORD));
			holder.timeText.setText(map.get(TIME));
			holder.nameText.setText(map.get(ID));
			imageLoader.displayImage(map.get(THUMB), holder.thumbView, squareOptions, animateFirstListener);
			//convertView.setOnClickListener(new ItemClickListener(map));

			return convertView;
		}

		@Override
		public int getCount() {
			return this.data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		private void handlerOneImage(ViewHolder viewHolder, Image image) {
			int totalWidth;
			int imageWidth;
			int imageHeight;
			ScreenTools screentools = ScreenTools.instance(self);
			totalWidth = screentools.getScreenWidth() - screentools.dip2px(80);
			imageWidth = screentools.dip2px(image.getWidth());
			imageHeight = screentools.dip2px(image.getHeight());
			if (image.getWidth() <= image.getHeight()) {
				if (imageHeight > totalWidth) {
					imageHeight = totalWidth;
					imageWidth = (imageHeight * image.getWidth()) / image.getHeight();
				}
			} else {
				if (imageWidth > totalWidth) {
					imageWidth = totalWidth;
					imageHeight = (imageWidth * image.getHeight()) / image.getWidth();
				}
			}
			ViewGroup.LayoutParams layoutparams = viewHolder.ivOne.getLayoutParams();
			layoutparams.height = imageHeight;
			layoutparams.width = imageWidth;
			viewHolder.ivOne.setLayoutParams(layoutparams);
			viewHolder.ivOne.setClickable(true);
			viewHolder.ivOne.setScaleType(android.widget.ImageView.ScaleType.FIT_XY);
			//imageLoader.displayImage(image.getUrl(), viewHolder.ivOne, squareOptions, animateFirstListener);
			viewHolder.ivOne.setImageUrl(image.getUrl());

		}

	}

	static class ViewHolder {
		public TextView wordText;
		public TextView timeText;
		public TextView nameText;
		public ImageView thumbView;
		public NineGridlayout ivMore;
		public CustomImageView ivOne;

	}

	// / 写一个通用的类。
	class DownloadCommentHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private MessageAdapter messageAdapter;
		// private List<Map<String, String>> data;

		private boolean isRefresh;

		public DownloadCommentHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, MessageAdapter messageAdapter, boolean isRefresh) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;

			this.messageAdapter = messageAdapter;
			this.isRefresh = isRefresh;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			listView.setRefreshSuccess("加载失败");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseStr) {
			try {
				System.out.println(new String(responseStr));
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, CommentRecords.class);
				ResponseResult<CommentRecords> result = getObjectMapper().readValue(new String(responseStr), javaType);

				List<Map<String, String>> downloadData = new ArrayList<Map<String, String>>();
				//设置 data
				downloadData = setData(result);

				// 设置data ends

				data.addAll(downloadData);
				if (!isRefresh) {

					listView.setAdapter(messageAdapter);
					// listView.refresh(); // 主动下拉刷新
					//					waitViewGroup.removeAllViews();
					waitViewGroup.addView(container);

				} else {
					// 刷新

					messageAdapter.data = data;
					messageAdapter.notifyDataSetChanged();
					listView.setRefreshSuccess("加载成功"); // 通知加载成功
					// 开启 加载更多多 的功能
					//listView.startLoadMore();
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	// / 写一个通用的类。
	class DownloadMoreCommentHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private MessageAdapter messageAdapter;
		private List<Map<String, String>> data;

		public DownloadMoreCommentHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, MessageAdapter messageAdapter, List<Map<String, String>> data) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			this.data = data;
			this.messageAdapter = messageAdapter;

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			AgainPlayer.makeCall((Activity) self, "网络异常");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseStr) {
			try {
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, CommentRecords.class);
				ResponseResult<CommentRecords> result = getObjectMapper().readValue(new String(responseStr), javaType);

				List<Map<String, String>> downloaddata = new ArrayList<Map<String, String>>();
				//设置 data
				downloaddata = setData(result);

				if (downloaddata.size() == 0) {
					listView.stopLoadMore();
				} else {
					data.addAll(downloaddata);
					messageAdapter.notifyDataSetChanged();
					listView.setLoadMoreSuccess(); // 通知加载成功
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	private List<Map<String, String>> setData(ResponseResult<CommentRecords> result) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (Comment comment : result.getObject().getRecordList()) {
			Map<String, String> map = new HashMap<String, String>();
			// 计算时间 。。几分钟前，几小时前。等等
			map.put(TIME, RelativeDateFormat.format(comment.getPostTime()));
			map.put(IMAGE, comment.getImages());
			map.put(WORD, comment.getWord());
			map.put(ID, comment.getUser_id());
//			map.put(THUMB, comment.getUser_id());
			map.put(THUMB, baseImageURL+comment.getUser_image()+"?p=0");
			list.add(map);
		}
		return list;

	}

}